# Create your views here.
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib.auth.models import User
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth import authenticate,logout,login
from django.template import RequestContext
from django.utils import simplejson

from online_shop.users.forms import *
from online_shop.users.models import comments, replys
from online_shop.products.models import products
from online_shop.orders.models import address, orders, order_details
from online_shop.products.views import get_recent_viewed_object
from online_shop.cart import cart

def user_panel_main(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/')
    variables = RequestContext(request,{})
    return render_to_response(
        'User_panel/user-panel-main.html',
        variables,
    )
        

def user_check_login(request):
    result = {}
    postdata = request.POST.copy()
    username = postdata['username']
    password = postdata['password']
    result['success'] = True
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            result['success'] = True
            login(request,user)
        else:
            result['success'] = False
            result['error_message'] = "Your account has been disabled!"
    else:
        result['success'] = False
        result['error_message'] = "Your username and password were incorrect."
    return HttpResponse(simplejson.dumps(result), mimetype='application/json')
   
def user_page(request, username):
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise Http404(u'Requested user not found.')
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/')
    email = user.email
    variables = RequestContext(request, {
      'username': username,
      'email': email,
      'recent_viewed': get_recent_viewed_object(request),
      'amount': cart.cart_distinct_item_count(request),
    })
    return render_to_response('user_page.html', variables)

def logout_page(request):
    logout(request)
    return HttpResponseRedirect('/')
    
def register_page(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
                email=form.cleaned_data['email']
            )
            user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
            login(request, user)
            return HttpResponseRedirect('/user_panel/')
    else:
        form = RegistrationForm()
    variables = RequestContext(request, {
        'form':form
    })
    return render_to_response(
        'registration/register.html',
        variables
    )
    
def modify_personal_info(request):
    if request.method == 'POST':
        if not request.user.is_authenticated():
            return HttpResponseRedirect('/login/')
        try:
            user = User.objects.get(username=request.user.username)
        except User.DoesNotExist:
            raise Http404(u'Requested user not found.')
        form = PersonalInfo(request.POST)
        if form.is_valid():
            user.email=form.cleaned_data['email']
            user.first_name = form.cleaned_data['firstName']
            user.last_name = form.cleaned_data['lastName']
            user.save()
            return HttpResponseRedirect('/user_panel/')
    else:
        user = request.user
        data = {
            'email': user.email,
            'firstName': user.first_name,
            'lastName': user.last_name
        }
        form = PersonalInfo(data)
    variables = RequestContext(request, {
        'form':form,
        'recent_viewed': get_recent_viewed_object(request),
    })
    return render_to_response(
        'User_panel/Account_Management/personal_info.html',
        variables
    )
def comments_and_replys(request):
    try:
        user = User.objects.get(username=request.user.username)
    except User.DoesNotExist:
        raise Http404(u'Requested user not found.')
    current_user_comments = user.comments_user.all()
    replys = user.replys_user.all()
    products_list = []
    replys_comments_list = []
    replys_products_list = []
    for comment in current_user_comments:
        product = products.objects.get(id=comment.product.id)
        products_list.append(product)
    for reply in replys:
        comment = comments.objects.get(id=reply.comment)
        replys_comments_list.append(comment)
    for comment in replys_comments_list:
        product = products.objects.get(id=comment.product.id)
        replys_products_list.append(product)
    variables = RequestContext(request, {
        'comments':current_user_comments,
        'products':products_list,
        'replys_comments':replys_comments_list,
        'replys_products':replys_products_list,
        'replys':replys,
        'recent_viewed': get_recent_viewed_object(request),
    })
    return render_to_response(
        'User_panel/My Comments/comments.html',
        variables
    )
def modify_delivery_address(request):
    user = User.objects.get(username=request.user.username)
    my_delivery_addresses = address.objects.filter(user=user)
    result = {}
    if request.method == 'POST':
        postdata = request.POST.copy()
        if postdata['submit'] == 'add':
            address_id = postdata.get('address_id',0)
            consignee = postdata['consignee']
            street_address = postdata['street_address']
            postal_code = postdata['postal_code']
            city = postdata['city']
            state = postdata.get('state','')
            country = postdata['country']
            phone = postdata['phone']
            if address_id==0:
                for my_address in my_delivery_addresses:
                    if my_address.address==street_address and my_address.city==city and my_address.country==country:
                        result['success'] = False
                        return HttpResponse(simplejson.dumps(result), mimetype='application/json')
                
                new_address = address()
                new_address.user_id = user.id
                new_address.name = consignee
                new_address.address = street_address
                new_address.postnumber = postal_code
                new_address.city = city
                new_address.state = state
                new_address.country = country
                new_address.phone = phone
                new_address.save()
                
                result['success'] = True
                result['address_id'] = new_address.id
                return HttpResponse(simplejson.dumps(result), mimetype='application/json')
            elif not address_id==0:
                my_address = get_object_or_404(address, id=address_id)
                my_address.user_id = user.id
                my_address.name = consignee
                my_address.address = street_address
                my_address.postnumber = postal_code
                my_address.city = city
                my_address.state = state
                my_address.country = country
                my_address.phone = phone
                my_address.save()
                result['success'] = True
                result['address_id'] = my_address.id
                return HttpResponse(simplejson.dumps(result), mimetype='application/json')
                
                
        
        if postdata['submit'] == 'delete':
            address_id = postdata['address_id']
            my_address = get_object_or_404(address, id=address_id)
            if my_address:
                my_address.delete()
                address_amount = address.objects.filter(user=user).count()
                result['success'] = True
                result['address_amount'] = address_amount
                return HttpResponse(simplejson.dumps(result), mimetype='application/json')
            
        if postdata['submit'] == 'modify':
            address_id = postdata['address_id']
            my_address = get_object_or_404(address, id=address_id)
            if my_address:
                result['success'] = True
                result['address_id'] = my_address.id
                result['consignee'] = my_address.name
                result['street_address'] = my_address.address
                result['postal_code'] = my_address.postnumber
                result['city'] = my_address.city
                result['state'] = my_address.state
                result['country'] = my_address.country
                result['phone'] = my_address.phone
                return HttpResponse(simplejson.dumps(result), mimetype='application/json')
        
    form = DeliverAddress()
    variables = RequestContext(request, {
        'form':form,
        'my_addresses': my_delivery_addresses
    })
    return render_to_response(
        'User_panel/Account_Management/delivery_address.html',
        variables
    )

def bought_goods(request, category):
    user = User.objects.get(username = request.user.username)
    my_orders = orders.objects.filter(iduser=user)
    bought_goods = []
    bought_goods_filter = []
    for my_order in my_orders:
        if my_order.status.type=='ARRIVED' or my_order.status.type=='FINISHED':
            my_order_details = order_details.objects.filter(idorder=my_order)
            for my_order_detail in my_order_details:
                good = my_order_detail.idproduct
                new_good_or_not = True
                for bought_good in bought_goods:
                    if good == bought_good:
                        new_good_or_not = False
                        break
                if new_good_or_not:
                    bought_goods.append(good)
    length = len(bought_goods)
    if not category=='all':
        for bought_good in bought_goods:
            if bought_good.subcategory.category.name==category:
                bought_goods_filter.append(bought_good)
    else:
        bought_goods_filter = bought_goods
    variables = RequestContext(request,{
        'bought_goods': bought_goods,
        'bought_goods_filter': bought_goods_filter,
        'length': length,
    })
    return render_to_response(
        'User_panel/my_goods/bought_goods.html',
        variables,
    )

def favourite_goods(request, category):
    user = User.objects.get(username = request.user.username)
    my_favourite_goods = user.favourite_user.all()
    length = len(my_favourite_goods)
    favourite_goods_filter = []
    if not category=='all':
        for favourite_good in my_favourite_goods:
            if favourite_good.product.subcategory.category.name == category:
                favourite_goods_filter.append(favourite_good)
    else:
        favourite_goods_filter = my_favourite_goods
    variables = RequestContext(request, {
        'favourite_goods': my_favourite_goods,
        'favourite_goods_filter': favourite_goods_filter,
        'length': length,
    })
    return render_to_response(
        'User_panel/my_goods/favourite_goods.html',
        variables,
    )

def uncomment_goods_list(request):
    user = User.objects.get(username = request.user.username)
    my_orders = orders.objects.filter(iduser=user)
    bought_goods = []
    uncomment_goods = []
    for my_order in my_orders:
        if my_order.status.type=='ARRIVED':
            my_order_details = order_details.objects.filter(idorder=my_order)
            for my_order_detail in my_order_details:
                if len(comments.objects.filter(order_detail=my_order_detail))==0:
                    new_good = True
                    for uncomment_good in uncomment_goods:
                        if my_order_detail.idproduct==uncomment_good.idproduct:
                            new_good = False
                    if new_good:
                        uncomment_goods.append(my_order_detail)
    length = len(uncomment_goods)
    variables = RequestContext(request,{
        'length':length,
        'uncomment_goods':uncomment_goods,
    })
    return render_to_response(
        'User_panel/my_goods/uncomment_goods.html',
        variables,
    )
    